package com.chendx.store.user.mq.listener;

import com.alibaba.fastjson.JSON;
import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.store.user.config.ApplicationContextProvider;
import com.chendx.store.user.netty.CustomerWebSocketHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by chendx on 2022/4/24.
 */
@Component
public class CustomerNoticeListener implements ChannelAwareMessageListener {

    private static ObjectMapper MAPPER = new ObjectMapper();
    private StringRedisTemplate redisTemplate = ApplicationContextProvider.getApplicationContext().getBean(StringRedisTemplate.class);
    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        MessageProperties messageProperties = message.getMessageProperties();
        String notice = new String(message.getBody(), Charset.defaultCharset());

        Map param = JSON.parseObject(notice,Map.class);

        String queueName = messageProperties.getConsumerQueue();
        String username = (String) param.get("username");
        String customer = (String) param.get("customer");
       // String username = queueName.substring(0,queueName.indexOf("_"));
       // String customer = queueName.substring(queueName.lastIndexOf("_") + 1);
        io.netty.channel.Channel wsChannel = CustomerWebSocketHandler.webSocketMap.get(customer);
        if (wsChannel != null){
            String key = "chat:"+customer +"_no_read_notice_count_for_" + username;
            redisTemplate.boundHashOps(key).increment(username,1);
            HashMap countMap = new HashMap();
            Map map = new HashMap<>();
            map.put("customer",customer);
            map.put("username",username);
            map.put("count",1);
            countMap.put("customerNoticeCount", 1);
            countMap.put("customerNoticeMap", map);
            countMap.put("notice",notice);
            ResponseResult responseResult = ResponseResult.okResult(countMap);
            //把数据通过WebSocket连接主动推送用户
            wsChannel.writeAndFlush(new TextWebSocketFrame(MAPPER.writeValueAsString(responseResult)));
        }
    }
}
